<template>
  <div class="public">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>

      <el-form-item label="密  码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >
        <!-- 第三方 -->
        <el-button
          type="danger"
          @click="giteeLogin"
          icon="el-icon-platform-eleme"
          circle
        ></el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { apiLogin, apigiteeLogin } from "@/api";
import Cookie from "js-cookie";
export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        // 校验规则
        username: [
          // 多个校验规则
          { required: true, message: "请输入用户名", target: "blur" },
        ],
        password: [{ required: true, message: "请输入用户名", target: "blur" }],
      },
    };
  },

  // 页面初始化后
  created() {
    // 获取地址栏参数
    if (this.$route.query.code) {
      // 用户已经授权
      const code = this.$route.query.code;

      // 发送请求 将code传给后端，
      apigiteeLogin({ code }).then((res) => {
        // 将token保存到cookie中
        Cookie.set("token", res.token);

        this.$message({
          type: "success", // success error warning
          message: "登录成功",
        });

        // 跳转页面
        window.location.href = "/";
      });
    }
  },

  methods: {
    submitForm(formName) {
      // 通过表单实例 触发验证
      //   validate： 验证表单的方法
      this.$refs[formName].validate((valid) => {
        // valid: boolean  校验的结果 true校验成功 false 校验失败
        if (valid) {
          apiLogin(this.ruleForm).then((res) => {
            // 将token保存到cookie中
            Cookie.set("token", res.token);

            this.$message({
              type: "success", // success error warning
              message: "登录成功",
            });

            // 跳转页面
            window.location.href = "/";
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    giteeLogin() {
      // 跳转到第三方授权页面
      window.location.href =
        "https://gitee.com/oauth/authorize?client_id=5e25a35a9736c3c1577af47c7e37238e9bc634272ef0b7e76d062a7438de085c&redirect_uri=http://192.168.137.243:8080/login&response_type=code";
    },
  },
};
</script>